﻿package com.gengine.core.call
{
    import com.gengine.utils.*;
    import flash.utils.*;

    public class Caller extends Object implements ICaller
    {
        private var _callerMap:Dictionary;

        public function Caller()
        {
            this._callerMap = new Dictionary(true);
        }

        public function addCall(type:Object, fun:Function) : void
        {
            var list:Array = this.getlistByType(type);
			list.push(fun);
        }

        public function removeCall(key:Object, fun:Function) : void
        {
            var arr:Array = this._callerMap[key] as Array;
            if (arr && arr.length > 0)
            {
                ArrayUtil.removeItem(arr, fun);
            }
        }

        public function call(key:Object, ... args) : Boolean
        {
            var fun:Function = null;
            args = this._callerMap[key] as Array;
            if (args && args.length > 0)
            {
                for each (fun in args)
                {
                    
					fun.apply(null, args);
                }
            }
            return true;
        }

        public function dispose() : void
        {
            var arr:Array = null;
            var item:String = null;
            for (item in this._callerMap)
            {
                
				arr = this._callerMap[item] as Array;
				arr.length = 0;
                delete this._callerMap[item];
            }
        }

        private function getlistByType(type:Object) : Array
        {
            if (type in this._callerMap)
            {
                return this._callerMap[type];
            }
			
            this._callerMap[type] = [];
            return _callerMap[type];
        }

        public function removeCallByType(key:Object) : void
        {
            var arr:Array = this._callerMap[key] as Array;
            if (arr)
            {
				arr.length = 0;
                delete this._callerMap[key];
            }
        }

        public function hasCall(target:Object) : Boolean
        {
            return (target in this._callerMap);
        }

    }
}
